<template>
  <div class="background-video-container">
    <!-- 视频元素 -->
    <video
      v-if="!showFallback"
      ref="videoRef"
      :src="videoSrc"
      autoplay
      loop
      muted
      playsinline
      preload="auto"
      @error="handleVideoError"
      @loadeddata="handleVideoLoaded"
      @canplay="handleVideoCanPlay"
      @pause="handleVideoPause"
      class="background-video"
    ></video>
    
    <!-- 备用图片 -->
    <div v-else class="fallback-image" :style="{ backgroundImage: `url(${fallbackImage})` }"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 组件属性
const props = defineProps({
  videoSrc: {
    type: String,
    default: '/video/background-video.webm'
  },
  fallbackImage: {
    type: String,
    default: '/images/theme/shape-menu-normal.svg'
  }
})

// 响应式状态
const videoRef = ref(null)
const showFallback = ref(false)
const isVideoLoaded = ref(false)
const playAttempts = ref(0)
const maxPlayAttempts = 3

// 视频错误处理
const handleVideoError = (e) => {
  console.error('视频加载失败:', e)
  showFallback.value = true
}

// 视频加载成功处理
const handleVideoLoaded = () => {
  console.log('视频加载成功')
  isVideoLoaded.value = true
  
  // 确保视频播放
  playVideo()
}

// 视频可以播放时处理
const handleVideoCanPlay = () => {
  console.log('视频可以播放')
  playVideo()
}

// 视频暂停时处理
const handleVideoPause = () => {
  console.log('视频暂停')
  // 检查是否是节能策略导致的暂停
  if (videoRef.value && !videoRef.value.ended && !videoRef.value.paused) {
    // 尝试恢复播放
    playVideo()
  }
}

// 播放视频
const playVideo = () => {
  if (!videoRef.value) return
  
  videoRef.value.play().catch(err => {
    console.error('视频播放失败:', err)
    playAttempts.value++
    
    // 如果是节能策略导致的暂停，尝试使用用户交互来恢复播放
    if (err.message && err.message.includes('background media was paused to save power')) {
      console.log('检测到节能策略暂停，等待用户交互后恢复播放')
      // 添加一次性点击事件监听器
      const resumeOnInteraction = () => {
        if (videoRef.value) {
          videoRef.value.play().catch(e => console.error('恢复播放失败:', e))
        }
        document.removeEventListener('click', resumeOnInteraction)
        document.removeEventListener('touchstart', resumeOnInteraction)
      }
      document.addEventListener('click', resumeOnInteraction)
      document.addEventListener('touchstart', resumeOnInteraction)
    }
    
    // 如果多次尝试播放失败，显示备用图片
    if (playAttempts.value >= maxPlayAttempts) {
      console.log('多次尝试播放失败，显示备用图片')
      showFallback.value = true
    }
  })
}

// 组件挂载时
onMounted(() => {
  // 确保视频在组件挂载后播放
  setTimeout(() => {
    if (videoRef.value && !isVideoLoaded.value) {
      playVideo()
    }
  }, 1000)
  
  // 监听页面可见性变化，确保在页面可见时视频播放
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible' && videoRef.value && !showFallback.value) {
      playVideo()
    }
  })
  
  // 添加用户交互事件监听，用于恢复被节能策略暂停的视频
  const resumeVideoOnInteraction = () => {
    if (videoRef.value && videoRef.value.paused && !showFallback.value) {
      playVideo()
    }
  }
  
  // 监听用户交互事件
  document.addEventListener('click', resumeVideoOnInteraction)
  document.addEventListener('touchstart', resumeVideoOnInteraction)
  document.addEventListener('keydown', resumeVideoOnInteraction)
})

// 组件卸载时
onUnmounted(() => {
  // 移除事件监听器
  document.removeEventListener('visibilitychange', () => {})
  document.removeEventListener('click', () => {})
  document.removeEventListener('touchstart', () => {})
  document.removeEventListener('keydown', () => {})
})
</script>

<style lang="scss" scoped>
.background-video-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  overflow: hidden;
}

.background-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.fallback-image {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.hero-content {
  position: absolute;
  top: 75%;
  left: 5%;
  transform: translateY(-50%);
  text-align: left;
  color: #fff;
  z-index: 2;
  width: auto;
  max-width: 800px;
  padding: 0;

  .hero-title {
    font-size: 64px;
    font-weight: 900;
    margin-bottom: 20px;
    letter-spacing: 2px;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
    animation: fadeInUp 1s ease-out;
  }

  .hero-subtitle {
    font-size: 24px;
    font-weight: 400;
    margin-bottom: 30px;
    letter-spacing: 1px;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
    animation: fadeInUp 1s ease-out 0.3s;
    opacity: 0;
    animation-fill-mode: forwards;
  }

  .hero-button {
    background-color: #fff;
    border: 1px solid #fff;
    color: #0b0c0d;
    display: inline-block;
    height: 50px;
    font-family: Lab Grotesque, Helvetica, Arial, sans-serif;
    text-decoration: none;
    padding: 12px 36px;
    font-size: 18px;
    font-weight: 600;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
    animation: fadeInUp 1s ease-out 0.6s;
    opacity: 0;
    animation-fill-mode: forwards;

    &:hover {
      background-color: rgba(255, 255, 255, 0.9);
      transform: translateY(-2px);
    }
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
